import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Spin, Button, Input, Radio, DatePicker } from 'antd';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import router from 'umi/router';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import FileReader from '@/components/FileReader';
import AdButton from '@/components/AdButton';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import moment from 'moment';
import {
  formItemFragement,
  queryDict,
  filterAddFile,
  filterDeteteFile,
  formatPrice,
} from '@/utils/common';
import { columnsUser, columnsDriver, supplierColumns, checkStrLength } from '@/pages/Common/common';
import { allDictList } from '@/utils/constans';
import {
  selectIncidentalList,
  selectIncidentalDetailAndInfo,
  routeUrl,
  codes,
  allDispatchType,
  incidentalStatusList,
  allUrl,
} from './utils';

const { TextArea } = Input;
const dateFormat = 'YYYY-MM-DD';
const dateFormatByM = 'YYYY-MM';
const { MonthPicker } = DatePicker;

@connect(({ incidental, component, loading, common }) => ({
  incidentalDetail: incidental.incidentalDetail,
  dictObject: component.dictObject,
  formValues: incidental.formValues,
  loading: loading.effects[allDispatchType.detail],
}))
@Form.create()
export default class IncidentalOperate extends Component {
  state = {
    detailId: '',
    type: '',
    disabled: false,
    relation: [],
    company: [],
    newReciverType: '',
  };

  componentWillMount() {
    const allDict = [allDictList.otherFeeType, allDictList.currencyType, allDictList.costSubjects];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      incidentalDetail,
    } = this.props;
    this.handleStateChange([{ detailId: id }]);
    const detail = incidentalDetail[id];
    // if (detail) return;
    this.getIncidentalDetails(id);
  }
  getIncidentalDetails = id => {
    const {
      match: { params },
    } = this.props;
    const incidentalId = id || params.id;
    incidentalId &&
      selectIncidentalDetailAndInfo({
        type: allDispatchType.detail,
        payload: { id: incidentalId },
        props: this.props,
        callback: data => {
          const relation =
            data.receiverType == 'EMPLOYEE'
              ? [{ id: data.relationObjId, sysName: data.relationObj }]
              : [{ customerCode: data.relationObjId, customerName: data.relationObj }];

          this.setState({
            // disabled,
            company: [{ customerName: data.ownCompanyName, customerCode: data.ownCompanyId }],
            // drivers: [{ id: data.driverId }],
            newReciverType: data.receiverType,
            type: data.type,
            relation: relation,
          });
          // const disabled = (data.billStatus === '' || data.billStatus === 'CONFIRM') ? data.source !== 'MANAGE' ? true : data.status !== 'CONFIRM' : true
          this.handleStateChange([{ detailId: record.id }, { recordStatus }, { visible: true }]);
        },
      });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  setTabName = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/setTabsName',
      payload,
      callback: data => {
        if (!data) return;
        router.push(`${routeUrl.edit}/${payload.id}`);
      },
    });
  };

  /**
   * 操作数据
   */
  saveInfo = () => {
    const {
      form,
      dispatch,
      incidentalDetail,
      match: {
        params: { id },
      },
    } = this.props;
    const { company, relation } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      const {
        status,
        driverId,
        attaQuantity,
        settlementDate,
        ownCompanyId,
        happenTime,
        relationObjId,
        ...params
      } = values;
      if (attaQuantity) {
        params.fileTokens = filterAddFile(attaQuantity);
      }
      if (id) {
        params.id = id;
        if (attaQuantity) {
          params.deleteFileIds = filterDeteteFile(attaQuantity, incidentalDetail[id].fileList);
        }
      }
      params.settlementDate = settlementDate ? moment(settlementDate).format(dateFormatByM) : '';
      if (happenTime) params.happenTime = moment(happenTime).format(dateFormat);
      if (company.length > 0) {
        const ownCompanyId = company.map(v => {
          return v.customerCode;
        });
        params.ownCompanyId = ownCompanyId.join(',');
      } else {
        params.ownCompanyId = '';
      }

      /* 付款对象类型 receiverType （EMPLOYEE 员工、 SUPPLIER 供应商）
       * 付款对象名称: relationObj
       * 付款人 id
       * 付款对象：员工+供应商
       */
      if (relation && relation.length > 0) {
        const relationObjId = relation.map(v => {
          return v.id ? v.id : v.customerCode;
        });
        const relationObj = relation.map(v => {
          return v.sysName ? v.sysName : v.customerName;
        });
        //driverId 用于存放付款人id，为了保持开始开发的行车档案一致
        params.driverId = relationObjId.join(',');
        params.relationObj = relationObj.join(',');
      }
      // console.log('params==', params)
      // return; //测试
      this.dispatchOperate(params);
    });
  };

  dispatchOperate = params => {
    const { dispatch, formValues } = this.props;
    dispatch({
      type: allDispatchType.operate,
      payload: params,
      callback: data => {
        if (!data) return;
        const id = params.id;
        this.setState(preState => ({
          disabled: !preState.disabled,
        }));

        if (id) {
          this.getIncidentalDetails(id);
        } else {
          this.setTabName({
            id: data,
            isReplaceTab: true,
          });
        }
        selectIncidentalList({ payload: formValues, props: this.props });
      },
    });
  };

  headerOperate = () => {
    const {
      match: {
        params: { id },
      },
      incidentalDetail,
    } = this.props;
    const { disabled, detailId } = this.state;
    const detail = incidentalDetail[detailId] || {};
    // const isCONFIRM = detail.status ? (detail.billStatus === '' || detail.billStatus === 'CONFIRM') ? detail.source !== 'MANAGE' ? true : detail.status !== 'CONFIRM' : true : false
    return (
      <div>
        {!disabled ? (
          <>
            <Button.Group>
              <AdButton
                text="保存"
                type="primary"
                code={codes.add}
                onClick={() => this.saveInfo()}
              />
              {id && (
                <AdButton
                  onClick={() => {
                    this.setState(preState => ({
                      disabled: !preState.disabled,
                    }));
                  }}
                  text="取消"
                  code={id ? codes.edit : codes.add}
                />
              )}
            </Button.Group>
          </>
        ) : (
          <Button.Group>
            <AdButton
              onClick={() => {
                this.setState(preState => ({
                  disabled: !preState.disabled,
                }));
              }}
              text="编辑"
              type="primary"
              code={id ? codes.edit : codes.add}
            />
          </Button.Group>
        )}
      </div>
    );
  };

  getValue = (values, type) => {
    if (type === 'company') {
      this.setState({
        drivers: [],
      });
    }
    this.setState({
      [type]: values,
    });
  };

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };

  render() {
    const { detailId, company, disabled, newReciverType } = this.state;

    const { form, incidentalDetail, loading, dictObject } = this.props;
    const getFieldDecorator = form.getFieldDecorator;
    const detail = incidentalDetail[detailId] || {};
    const checkedTypeEmployee =
      (newReciverType || detail.receiverType) === 'EMPLOYEE' ? true : false;

    const editPageParams = {
      title: detail.miscellaneousNo || '新增杂费',
      headerOperate: this.headerOperate(),
      panelValue: [{ key: '基础信息' }],
    };

    console.log('relation====', this.state.relation);

    const commonParams = {
      getFieldDecorator,
    };
    const prefixSelector = (name, value) => (
      <AntdFormItem code={name} initialValue={value || 'CNY'} {...commonParams}>
        <AdSelect
          disabled={disabled}
          isExist={true}
          data={dictObject[allDictList.currencyType]}
          payload={{ code: allDictList.currencyType }}
          style={{ width: 90 }}
        />
      </AntdFormItem>
    );
    const formItem = [
      [
        <AntdFormItem
          label="单号"
          code="miscellaneousNo"
          initialValue={detail.miscellaneousNo}
          {...commonParams}
        >
          <AntdInput disabled={true} placeholder="保存后系统自动生成" />
        </AntdFormItem>,
        <AntdFormItem label="状态" code="status" initialValue={detail.status} {...commonParams}>
          <AdSelect isExist={true} data={incidentalStatusList} disabled={true} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="车次号"
          code="trainName"
          initialValue={detail.trainName}
          {...commonParams}
        >
          <AntdInput disabled={true} placeholder="自动更新" />
        </AntdFormItem>,
        <AntdFormItem
          label="所属公司"
          code="ownCompanyId"
          rules={[{ required: true }]}
          initialValue={detail.ownCompanyId || undefined}
          {...commonParams}
        >
          <SearchSelect
            dataUrl={allUrl.companyList}
            url={allUrl.userDetail}
            selectedData={company} // 选中值
            multiple={false} // 是否多选
            showValue="customerName"
            searchName="customerName"
            columns={supplierColumns} // 表格展示列
            onChange={values => this.getValue(values, 'company')} // 获取选中值
            scrollX={400}
            id="IncidentalOperate_2"
            disabled={disabled}
            allowClear={true}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="付款对象类型"
          code="receiverType"
          initialValue={detail.receiverType}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <Radio.Group
            onChange={e => {
              this.handleStateChange([{ newReciverType: e.target.value, relation: [] }]);
              form.resetFields(['relationObjId']);
            }}
          >
            <Radio value="EMPLOYEE" disabled={disabled}>
              员工
            </Radio>
            <Radio value="SUPPLIER" disabled={disabled}>
              供应商
            </Radio>
          </Radio.Group>
        </AntdFormItem>,
        <AntdFormItem
          label="付款对象"
          rules={[{ required: true }]}
          code="relationObjId"
          initialValue={detail.relationObjId}
          {...commonParams}
        >
          <SearchSelect
            // url={checkedTypeEmployee ? allUrl.userDetail : allUrl.supplierDetail}
            dataUrl={checkedTypeEmployee ? allUrl.userList : allUrl.supplierList}
            columns={checkedTypeEmployee ? columnsUser : supplierColumns}
            allowClear={true}
            multiple={false}
            id="incidentalOperate_1"
            showValue={checkedTypeEmployee ? 'sysName' : 'customerName'}
            searchName={checkedTypeEmployee ? 'keyWord' : 'customerName'}
            scrollX={400}
            onChange={values => this.getValue(values, 'relation')} // 获取选中值
            selectedData={this.state.relation} // 选中值
            disabled={disabled}
          />
        </AntdFormItem>,
      ],
      [
        // <AntdFormItem
        //   initialValue={drivers}
        //   rules={[{ required: true }]}
        //   label="付款人"
        //   code="driverId"
        //   {...commonParams}
        // >
        //   <SearchSelect
        //     dataUrl="/tms/tms-driver-incidental/selectDriverList"
        //     url="/tms/tms-driver-incidental/selectDriverView_s"
        //     multiple={false} // 是否多选
        //     selectedData={drivers} // 选中值
        //     columns={columnsDriver} // 表格展示列
        //     onChange={val => this.getValue(val, 'drivers')} // 获取选中值
        //     id="incidentalOperate_1"
        //     disabled={disabled}
        //     allowClear={true}
        //     payload={{ mdsCompanyId: company.length > 0 ? company[0].customerCode : '' }}
        //   // scrollX={350}
        //   />
        // </AntdFormItem>,
        <AntdFormItem
          label="费用类型"
          rules={[{ required: true }]}
          code="type"
          initialValue={detail.type}
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            isExist={true}
            data={dictObject[allDictList.otherFeeType]}
            payload={{ code: allDictList.otherFeeType }}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="科目"
          rules={[{ required: true }]}
          code="costType"
          initialValue={detail.costType}
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            isExist={true}
            data={dictObject[allDictList.costSubjects]}
            payload={{ code: allDictList.costSubjects }}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="付款日期"
          code="happenTime"
          rules={[{ required: true }]}
          initialValue={
            detail.happenTime ? moment(moment(detail.happenTime).format('YYYY-MM-DD')) : undefined
          }
          {...commonParams}
        >
          <AntdDatePicker disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="金额"
          code="fee"
          rules={[{ required: true }]}
          initialValue={detail.fee ? formatPrice(detail.fee) : ''}
          {...commonParams}
        >
          <AntdInput
            mode="money"
            disabled={disabled}
            addonBefore={prefixSelector('currency', detail.currency)}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="结算周期"
          code="settlementDate"
          rules={[{ required: true }]}
          initialValue={
            detail && detail.settlementDate ? moment(detail.settlementDate, dateFormatByM) : null
          }
          {...commonParams}
        >
          <MonthPicker disabled={disabled} style={{ width: '100%' }} />
        </AntdFormItem>,
        <AntdFormItem
          label="拖单号"
          code="transportNo"
          rules={[{ required: true }]}
          initialValue={detail.transportNo}
          {...commonParams}
        >
          <Input disabled={disabled}  />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="备注"
          code="remark"
          rules={[
            {
              validator: (rule, value, callback) => {
                checkStrLength(rule, value, callback, 200, '备注');
              },
            },
          ]}
          initialValue={detail.remark}
          {...commonParams}
        >
          <TextArea disabled={disabled} rows={4} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="附件"
          code="attaQuantity"
          initialValue={detail.fileList || []}
          {...commonParams}
        >
          <FileReader urlType="tms" disabled={disabled} />
        </AntdFormItem>,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <Spin spinning={detailId ? loading : false}>
          <AntdForm>{formItemFragement(formItem)}</AntdForm>
        </Spin>
      </EditPage>
    );
  }
}
